<template>
  <el-dialog :visible.sync="visible"
             :title="!dataForm.id ? `${$t('add')}权限` : `${$t('update')}权限`"
             :close-on-click-modal="false"
             :append-to-body="true"
             :before-close="closeDialog"
             class="add-or-updata"
             width="35%"
             :close-on-press-escape="false">
    <el-form :model="dataForm"
             v-loading='dataListLoading'
             ref="dataForm"
             label-position="left"
             style="overflow: hidden;"
             @keyup.enter.native="dataFormSubmitHandle()"
             label-width="110px">
      <el-form-item label="应用端"
                    :rules="required()"
                    prop="usePort">
        <el-select v-model="dataForm.usePort"
                   class="width-100"
                   @change="checkParentsList"
                   placeholder="请选择">
          <el-option v-for="item in modeOptions"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型"
                    :rules="required()"
                    prop="type">
        <el-select v-model="dataForm.type"
                   class="width-100"
                   @change="checkParentsList"
                   placeholder="请选择">
          <el-option v-for="item in typeOptions"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="menuName"
                    v-if="menuName !== ''"
                    :rules="required()"
                    prop="pid">
        <el-popover v-model.trim="deptListVisible"
                    ref="deptListPopover"
                    placement="bottom-start"
                    trigger="click">
          <el-tree :data="parentNameOptions"
                   :props="{ label: 'name', children: 'children' }"
                   node-key="id"
                   ref="deptListTree"
                   :highlight-current="true"
                   :expand-on-click-node="false"
                   accordion
                   @current-change="deptListTreeCurrentChangeHandle">
          </el-tree>
        </el-popover>
        <el-input v-model.trim="dataForm.deptName"
                  v-popover:deptListPopover
                  readonly
                  placeholder="请选择">
        </el-input>
      </el-form-item>

      <el-form-item label="名称"
                    prop="name"
                    :rules="stringRule(true, 2, 50)">
        <el-input v-model.trim="dataForm.name"
                  :placeholder="$t('menu.name')"></el-input>
      </el-form-item>
      <el-form-item label="路由"
                    v-if="dataForm.type === '1' && dataForm.type !== ''"
                    :rules="stringRule(false, 2, 100)"
                    prop="url">
        <el-input v-model.trim="dataForm.url"
                  :placeholder="$t('menu.url')"></el-input>
      </el-form-item>
      <el-form-item label="标识符"
                    v-if="dataForm.type !== '3' && dataForm.type !== '4'"
                    :rules="stringRule(isRequired, 2, 100)"
                    prop="identification">
        <el-input v-model.trim="dataForm.identification"
                  placeholder="标识符"></el-input>
      </el-form-item>
      <el-form-item label="HTTP地址"
                    v-if="dataForm.type === '3' && dataForm.type !== ''"
                    :rules="stringRule(true, 2, 100)"
                    prop="httpAddress">
        <el-input v-model.trim="dataForm.httpAddress"
                  placeholder=""></el-input>
      </el-form-item>
      <el-form-item label=""
                    v-if="dataForm.type === '3' && dataForm.type !== ''"
                    :rules="required()"
                    prop="singleSign">
        <el-radio-group v-model="dataForm.singleSign">
          <el-radio label="0">无需单点登录</el-radio>
          <el-radio label="1">finereport单点登录</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="URL参数字符串"
                    v-if="dataForm.type === '3' && dataForm.type !== ''"
                    :rules="stringRule(false, 1, 300)"
                    prop="urlParam">
        <el-input v-model.trim="dataForm.urlParam"
                  placeholder="例如：/run/GoSpJkI2xdNq/r_5Juefss?cps=expand&rps=expand&nav=1&ha=0&la=0&fc=0&out=1&rt=1"></el-input>
      </el-form-item>
      <el-form-item label="上传图片"
                    v-if="dataForm.type === '4' && dataForm.type !== ''"
                    prop="imgAddress"
                    :rules="required()">
        <file-upload reg=".(png|jpeg|jpg)$"
                     ref="fileUpload"
                     accept=".jpeg,.jpg,.png"
                     title="上传图片"
                     :limit="1"
                     :paramData="{ bucketName: 'menu/images' }"
                     action="/springbootApi/system/oss/upload"
                     uploadType="picture-card"
                     @success="successImgLoad"
                     @remove="handleImgRemove" />
        <div>建议尺寸为1160*824</div>
      </el-form-item>
      <el-form-item label="排序"
                    prop="sort">
        <el-input-number v-model.trim="dataForm.sort"
                         controls-position="right"
                         :max="255"
                         :min="0"
                         class="width-100"
                         :label="$t('menu.sort')"></el-input-number>
      </el-form-item>
      <el-form-item label="图标"
                    prop="icon"
                    v-if="dataForm.type !== '2' && dataForm.type !== ''"
                    class="icon-list">
        <el-popover v-model.trim="iconListVisible"
                    ref="iconListPopover"
                    placement="bottom-start"
                    trigger="click"
                    popper-class="mod-sys__menu-icon-popover">
          <div class="mod-sys__menu-icon-inner">
            <div class="mod-sys__menu-icon-list">
              <el-button v-for="(item, index) in iconList"
                         :key="index"
                         @click="iconListCurrentChangeHandle(item)"
                         :class="{ 'is-active': dataForm.icon === item }">
                <svg class="icon-svg"
                     aria-hidden="true">
                  <use :xlink:href="`#${item}`"></use>
                </svg>
              </el-button>
            </div>
          </div>
        </el-popover>
        <el-input v-model.trim="dataForm.icon"
                  v-popover:iconListPopover
                  :readonly="true"
                  :placeholder="$t('menu.icon')"></el-input>
        <i class="el-icon-close menu-close"
           @click="menuClose"></i>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="isShow"
                        v-if="dataForm.type !== '2' && dataForm.type !== ''">
            <el-checkbox true-label='1'
                         false-label='0'
                         v-model.trim="dataForm.isShow">是否显示菜单</el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="isExhibition"
                        class="isUser"
                        v-if="dataForm.type !== '2' && dataForm.type !== ''">
            <el-checkbox true-label='1'
                         false-label='0'
                         v-model.trim="dataForm.isExhibition">是否超级管理员权限</el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer">
      <el-button type="primary"
                 :loading="isRequest"
                 @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
      <el-button @click="closeDialog">{{ $t('cancel') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import formValidate from '@/mixins/form-validate'
import debounce from 'lodash/debounce'
import FileUpload from '@/components/file-upload/file-upload'
import { getIconList } from '@/utils'
export default {
  mixins: [mixinViewModule, formValidate],
  components: {
    FileUpload
  },
  data () {
    return {
      visible: false,
      isRequest: false,
      iconList: [],
      iconListVisible: false,
      mixinViewModuleOptions: {
        addURL: '/system/sysPermission/addPermission', // 添加或修改的接口
        updateURL: '/system/sysPermission/updatePermission', // 添加或修改的接口
        getDataInfoURL: '/system/sysPermission/getPermission?id=', // 获取详情的接口
        getParentsListURL: '/system/sysPermission/getPermissionList'// 获取查询板块或模块的列表
      },
      deptListVisible: false,
      // parentNameOptions: [],
      plateList: [], // 板块列表
      modeList: [], // 模块列表
      typeOptions: [{
        value: '0',
        label: '板块'
      }, {
        value: '1',
        label: '模块'
      }, {
        value: '2',
        label: '功能'
      }, {
        value: '3',
        label: '外部链接'
      }, {
        value: '4',
        label: '临时图片'
      }],
      modeOptions: [{
        value: 0,
        label: 'PC端'
      },
      //  {
      //   value: 1,
      //   label: 'Pad端'
      // },
      {
        value: 2,
        label: '企业App端'
      }],
      parentNameOptions: [],
      imgUrl: [],
      dataForm: {
        type: '0',
        name: '',
        pid: '',
        url: '',
        sort: 0,
        icon: '',
        isShow: '0',
        isExhibition: '0',
        identification: '',
        usePort: 0,
        imgAddress: '',
        urlParam: '',
        httpAddress: '',
        singleSign: '0'
      }
    }
  },
  computed: {
    isRequired () {
      return this.dataForm.type === '2'
    },
    menuName () {
      switch (this.dataForm.type) {
        case '0':
          return '上级板块'
        case '1':
          return '所属板块'
        case '2':
          return '所属模块'
        case '3':
          return '所属板块'
        case '4':
          return '所属板块'
        default:
          return ''
      }
    }
  },
  watch: {
    'dataForm.type' (val) {
      this.$refs['dataForm'].clearValidate()
    }
  },
  methods: {
    menuClose () {
      this.$set(this.dataForm, 'icon', '')
    },
    closeDialog () {
      this.$refs['dataForm'].resetFields()
      this.dataForm = Object.assign({}, {}, this.Initialization)
      this.visible = false
      this.isRequest = false
    },
    init (data) {
      data = data || {}
      this.dataForm.id = data.id
      this.dataForm.isShow = 0
      this.visible = true
      this.Initialization = JSON.parse(JSON.stringify(this.dataForm))
      this.$nextTick(() => {
        this.iconList = getIconList()
        this.dataForm.pid = '0'
        if (this.dataForm.id) {
          // 获取信息
          this.getDataInfo().then(res => {
            if (res.code !== 0) {
              return
            }
            let list = []
            list.push({
              name: res.data.imgAddress,
              url: `${res.data.imgAddress}`
            })
            if (res.data.imgAddress) {
              this.imgUrl.push(list[0].name)
              if (this.$refs.fileUpload) {
                this.$refs.fileUpload.init(list)
              }
            }
            this.getParentsList().then(() => {
              const selectMenu = this.parentNameOptions.filter(item => item.id === this.dataForm.pid)
              if (selectMenu.length) {
                this.dataForm.pid = selectMenu[0].id
              }
            })
            if (res.data.pid === '0') {
              this.dataForm.deptName = '顶级菜单'
            } else {
              this.dataForm.deptName = res.data.parentName
            }
          })
        } else {
          this.getParentsList()
        }
      })
    },
    // 上传成功
    successImgLoad (name, url) {
      this.dataForm.imgAddress = url
      this.imgUrl.push(url)
    },
    // 删除图片
    handleImgRemove (url) {
      this.deleteData({
        url: this.mixinViewModuleOptions.deleteImgURL,
        paramData: { files: url.url },
        isLoading: false
      })
      this.dataForm.imgAddress = ''
    },
    // 切换应用端或者类型
    checkParentsList () {
      this.dataForm.pid = ''
      this.dataForm.url = ''
      this.getParentsList()
    },
    // 上级部门树, 选中
    deptListTreeCurrentChangeHandle (data) {
      if (this.dataForm.id && data.id !== '0' && this.dataForm.type !== '2') {
        let deptItem = ''
        let bool = false

        if (data.id === this.dataForm.id) {
          this.$message.warning('禁止放置在自身以及其子菜单下面')
          return
        }

        if (data.topId !== '0') {
          deptItem = this.parentNameOptions.filter(item => item.id === data.topId)
        } else {
          deptItem = this.parentNameOptions.filter(item => item.id === data.id)
        }
        let selfItem = this.getDeptItem(this.dataForm.id, deptItem[0])

        if (selfItem) {
          bool = this.getDeptItem(data.id, selfItem)
        }

        if (bool) {
          this.$message.warning('禁止放置在自身以及其子菜单下面')
          return
        }
      }

      this.dataForm.deptName = data.name
      this.dataForm.pid = data.id
      this.deptListVisible = false
    },
    // 返回当前选中的部门本身以及所有的子级
    getDeptItem (id, deptItem) {
      let bool = false
      if (id === deptItem.id) {
        return deptItem
      }

      if (deptItem.children || deptItem.children.length) {
        deptItem.children.map(item => {
          if (bool) return bool
          bool = this.getDeptItem(id, item)
        })
      }

      return bool
    },
    // format(val){
    //   if (val === 0) {
    //     return '1'
    //   }else if(val === 1)
    // }
    getParentsList () {
      this.parentNameOptions = []
      return this.getData({
        url: this.mixinViewModuleOptions.getParentsListURL,
        paramData: {
          usePort: this.dataForm.usePort,
          type: this.dataForm.type === '2' ? '1' : '0'
        }
      }).then(res => {
        if (res.code !== 0) {
          return
        }
        if (this.dataForm.type === '0') {
          res.data.unshift({
            id: '0',
            name: '顶级菜单'
          })
        }
        this.parentNameOptions.push(...res.data)
      })
    },
    // 图标, 选中
    iconListCurrentChangeHandle (icon) {
      this.dataForm.icon = icon
      this.iconListVisible = false
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          // this.dataForm.isShow = this.dataForm.isShow === 'true'
          const url = this.dataForm.id ? this.mixinViewModuleOptions.updateURL : this.mixinViewModuleOptions.addURL
          let params = {}
          params = Object.assign({}, {}, this.dataForm)
          if (this.dataForm.type !== '2' && params.identification === '') {
            delete params.identification
          }
          this.addOrUpdateItem({ url, paramData: params }).then(res => {
            this.isRequest = false
            if (res.code !== 0) { return }
            this.$emit('callBack')
            this.closeDialog()
          })
        }
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">
.menu-close {
  position: absolute;
  top: 35%;
  right: 1%;
  cursor: pointer;
}

.mod-sys__menu {

  .menu-list,
  .icon-list {
    position: relative;

    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }

  &-icon-popover {
    width: 458px;
    overflow: hidden;
  }

  &-icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }

  &-icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;

    >.el-button {
      padding: 8px;
      margin: 8px 0 0 8px;

      >span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
}

.el-col .isUser .el-form-item__content {
  margin-left: 70px !important;
}
</style>
